use std::io;

use actix_files as fs;
use actix_web::{web, App, HttpResponse, HttpServer, Responder};

use super::*;
use info::Info;

fn jpg(info: web::Path<Info>) -> impl Responder {
    let tile_data = select_tile_data(&info.tiles, info.z, info.x, info.y);
    HttpResponse::Ok()
        .content_type("image/jpeg")
        .body(tile_data)
}

fn png(info: web::Path<Info>) -> impl Responder {
    let tile_data = select_tile_data(&info.tiles, info.z, info.x, info.y);
    HttpResponse::Ok()
        .content_type("image/png")
        .body(tile_data)

}

/// http server的启动方法
/// `addr` 是http服务要绑定的ip和端口
pub fn start(addr: &str) -> io::Result<()> {
    HttpServer::new(|| {
    App::new()
    .route(r"/mbtiles/{tiles}/{z}/{x}/{y}.jpg", web::get().to(jpg))
    .route(r"/mbtiles/{tiles}/{z}/{x}/{y}.png", web::get().to(png))
    .service(fs::Files::new("/tiles", "./tiles/").show_files_listing())
    })
    .bind(addr)?.run()?;
    Ok(())
}